﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lswweb.IDAL;
using Lswweb.Model;
using Lswweb.Domain;

namespace Lswweb.Domain
{
    public class ProductWholesaleRule
    {
        #region Static Methods

        private static IProductWholesaleRuleDAL dal = DALFactory.CreateProductWholesaleRuleDAL();

        public static ProductWholesaleRuleInfo GetWholesaleRule(int id)
        {
            if (id <= 0)
                return null;

            return ProductWholesaleRule.dal.FindById(id);
        }

        public static IList<ProductWholesaleRuleInfo> FindAll()
        {
            return ProductWholesaleRule.dal.FindAll();
        }

        public static void Insert(ProductWholesaleRuleInfo info)
        {
            if (info == null)
            {
                SiteContext.RenderMessage(ExceptionType.UnknownError);
                return;
            }

            try
            {
                dal.Add(info);
                SiteContext.RenderMessage(ExceptionType.HandleSuccess);
            }
            catch
            {
                SiteContext.RenderMessage(ExceptionType.UnknownError);

            }
        }

        public static void Update(ProductWholesaleRuleInfo info)
        {
            if (info == null)
            {
                SiteContext.RenderMessage(ExceptionType.UnknownError);
                return;
            }

            try
            {
                dal.Update(info);
                SiteContext.RenderMessage(ExceptionType.HandleSuccess);
            }
            catch
            {
                SiteContext.RenderMessage(ExceptionType.UnknownError);

            }
        }

        public static void Delete(int id)
        {
            if (id <= 0)
            {
                SiteContext.RenderMessage(ExceptionType.UnknownError);
                return;
            }

            try
            {
                dal.Delete(id);
                SiteContext.RenderMessage(ExceptionType.HandleSuccess);
            }
            catch
            {
                SiteContext.RenderMessage(ExceptionType.UnknownError);
            }
        }

        #endregion

        public static decimal PriceCalculation(int quantity, decimal originalPrice)
        {
            ProductWholesaleRuleInfo rule = dal.FindByQuantity(quantity);
            if (rule == null)
                return originalPrice;

            return Math.Round(rule.PriceRate * originalPrice / 100, 2);
        }
        public static decimal PriceCalculation(decimal originalPrice)
        {
            ProductWholesaleRuleInfo rule = dal.FindAll().OrderBy(info => info.MinNumber).LastOrDefault();
            if (rule == null)
                return originalPrice;

            return Math.Round(rule.PriceRate * originalPrice / 100, 2);
        }
    }
}
